import 'package:flutter/material.dart';
import 'package:orginone/dart/base/ui.dart';
import 'package:orginone/utils/log/log_util.dart';
import 'package:provider/provider.dart';
import '../main.dart';
import 'router_const.dart';

/// 路由参数
class RouterParam {
  /// 模块名称
  late String modelName;

  /// 上级路由参数
  List<RouterParam> parents;

  /// 默认激活页签
  List<String> defaultActiveTabs;

  /// 路由穿参
  dynamic datas;

  RouterParam(
      {String? modelName,
      this.parents = const [],
      this.defaultActiveTabs = const [],
      this.datas}) {
    this.modelName = modelName ?? relationCtrl.homeEnum.value.label;
  }
}

/// 页面导航数据
class AppRoute<R extends Route<dynamic>> extends RouteObserver<R>
    with ChangeNotifier {
  //当前页面数据
  late PageData currPageData;
  //历史页面数据
  late List<PageData> pageHistorys;
  //是否显示底部TabBar
  bool showBottomTabBar;
  //头像点击事件
  Function()? onTap;

  AppRoute({this.showBottomTabBar = true}) {
    pageHistorys = [];
    currPageData = PageData();
  }

  //判断是否有更多实体
  bool get hasMore {
    return null != currPageData.entitys &&
        (currPageData.entitys?.isNotEmpty ?? false);
  }

  //是首页
  bool isHomePage() {
    return pageHistorys.isEmpty;
  }

  // /// 路由切换（不记录历史）
  // void to(String path,
  //     {String? title,
  //     IEntity? entity,
  //     List<IEntity>? entitys,
  //     ButtonGroupData? operations,
  //     dynamic data,
  //     bool showBottomTabBar = true}) {
  //   _setData(
  //       title: title,
  //       entity: entity,
  //       entitys: entitys,
  //       operations: operations,
  //       data: data,
  //       showBottomTabBar: showBottomTabBar,
  //       recordHistory: false);

  //   if (null != navigatorKey.currentState) {
  //     Navigator.of(navigatorKey.currentState!.context).pushNamedAndRemoveUntil(
  //         path, (Route<dynamic> route) => false,
  //         arguments: this);
  //   }
  // }

  void setData(
      {String? title,
      IEntityUI? entity,
      List<IEntityUI>? entitys,
      ButtonGroupData? operations,
      dynamic data,
      Widget? child,
      bool showBottomTabBar = true}) {
    _setData(
        PageData(
            path: currPageData.path,
            title: title,
            entity: entity,
            entitys: entitys,
            operations: operations,
            data: data,
            child: child),
        showBottomTabBar: showBottomTabBar,
        recordHistory: false);
    if (showBottomTabBar) {
      pageHistorys.clear();
    }
    notifyListeners();
  }

  void _setData(PageData pageData,
      {bool showBottomTabBar = true, bool recordHistory = true}) {
    XLogUtil.dd(
        "did 路由参数设置 currPagePath:${currPageData.path} path:${pageData.path}");
    if (recordHistory) {
      pageHistorys.add(PageData(
          title: currPageData.title,
          path: currPageData.path,
          entity: currPageData.entity,
          entitys: currPageData.entitys,
          operations: currPageData.operations,
          data: currPageData.data,
          child: currPageData.child));
    }
    currPageData.path = pageData.path;
    currPageData.title = pageData.title;
    currPageData.entity = pageData.entity;
    currPageData.entitys = pageData.entitys;
    currPageData.operations = pageData.operations;
    currPageData.data = pageData.data;
    currPageData.child = pageData.child;
    this.showBottomTabBar = showBottomTabBar;
  }

  /// 路由切换（记录历史）
  Future<T?> go<T extends Object?>(BuildContext context, String? path,
      {String? title,
      IEntityUI? entity,
      List<IEntityUI>? entitys,
      ButtonGroupData? operations,
      dynamic data,
      Widget? child,
      bool showBottomTabBar = true}) {
    var currPath = currPageData.path;
    _setData(
        PageData(
            title: title,
            entity: entity,
            entitys: entitys,
            operations: operations,
            path: path,
            data: data,
            child: child),
        showBottomTabBar: showBottomTabBar);

    XLogUtil.dd("did 路由调整 currPath:$currPath path:$path");
    if (null != path && path != currPath) {
      if ([Routers.home, Routers.login, Routers.logintrans, Routers.errorGuide]
          .contains(path)) {
        if (null != navigatorKey.currentState && path != currPath) {
          pageHistorys.clear();
          return Navigator.of(navigatorKey.currentState!.context)
              .pushNamedAndRemoveUntil<T>(path, (Route<dynamic> route) => false,
                  arguments: this);
        }
      } else {
        return Navigator.pushNamed<T>(context, path, arguments: this);
      }
    } else if (null != child) {
      return Navigator.push<T>(context,
          MaterialPageRoute<T>(builder: (context) {
        return Provider(
          create: (context) => this,
          child: child,
        );
      }));
    } else {
      currPageData.path = currPath;
      notifyListeners();
    }
    return Future(() => null);
  }

  /// 路由回退到上一级
  PageData back<T extends Object?>([BuildContext? context]) {
    bool isCurrPage = false;
    if (pageHistorys.isNotEmpty) {
      PageData lastCurrPageData = pageHistorys.last;
      if (null != currPageData.path &&
          currPageData.path == lastCurrPageData.path) {
        isCurrPage = true;
      }
      _setData(lastCurrPageData, recordHistory: false);
      pageHistorys.removeLast();
    }
    if (null != context && !isCurrPage) {
      Navigator.pop<T>(context);
    }
    if (isCurrPage) {
      notifyListeners();
    }
    return currPageData;
  }

  /// 路由回退到上一级
  void remove<T extends Object?>(String path) {
    if (pageHistorys.isNotEmpty) {
      PageData lastCurrPageData = pageHistorys.last;

      _setData(lastCurrPageData, recordHistory: false);
      pageHistorys.removeLast();

      // PageData<dynamic>? history =
      //     pageHistorys.firstWhereOrNull((element) => element.path == path);
      // if (null != history) {
      //   pageHistorys.remove(history);
      // } else if (null == history) {
      //   pageHistorys.removeLast();
      // }
    }
  }
}

/// 页面数据
class PageData<T> {
  //标题
  late String? title;
  //当前实体
  late IEntityUI? entity;
  //实体集合
  late List<IEntityUI>? entitys;
  //页面路由
  late String? path;
  //页面数据
  late T? data;
  //操作集合
  late ButtonGroupData? operations;
  //组件
  Widget? child;
  PageData(
      {this.title,
      this.entity,
      this.entitys,
      this.operations,
      this.path,
      this.data,
      this.child});
}

///一组按钮数据
class ButtonGroupData extends ChangeNotifier {
  List<ButtonData> buttons;

  ButtonGroupData(this.buttons);

  void set(List<ButtonData> buttons) {
    this.buttons = buttons;
    notifyListeners();
  }
}

///按钮数据
class ButtonData {
  //按钮图标名称
  late String icon;
  //按钮名称
  late String name;
  //按钮操作
  late Function onTap;

  ButtonData(this.icon, this.name, this.onTap);
}
